import { asyncRoutes, constantRoutes } from '@/router'
import store from '../index'
import Layout from '@/layout'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
    if (route.meta && route.meta.roles) {
        return roles.some(role => route.meta.roles.includes(role))
    } else {
        return true
    }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
    const res = []

    routes.forEach(route => {
        const tmp = {...route }
        if (hasPermission(roles, tmp)) {
            if (tmp.children) {
                tmp.children = filterAsyncRoutes(tmp.children, roles)
            }
            res.push(tmp)
        }
    })

    return res
}


const state = {
    routes: [],
    addRoutes: []
}

const mutations = {
    SET_ROUTES: (state, args) => {
        console.log(args, "转换菜单")

        state.addRoutes = args

        state.routes = constantRoutes.concat(args)
    }
}



const actions = {
    generateRoutes({ commit }) {

        return new Promise(resolve => {

            const routers = [...store.state.user.menuList]

            commit('SET_ROUTES', routers)
            resolve(routers)
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}